//
//  DBProject.m
//  ppkc2016
//
//  Created by 拼凑的断音 on 16/4/16.
//  Copyright © 2016年 拼凑的断音. All rights reserved.
//

#import "DBProject.h"
#import "XXTool.h"

@interface DBProject ()

@property NSString *dataName;

@end

@implementation DBProject
{
    BOOL isCategoryUpdating;
    BOOL isCountryUpdating;
    BOOL isExhibitorInfoUpdating;
}

+(instancetype)shareDBProject
{
    static DBProject *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        instance.dataName = [instance realmDB];
    });
    return instance;
}

+(dispatch_queue_t)realmQueue
{
    static dispatch_queue_t queue = NULL;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        queue = dispatch_queue_create("RealmThread", 0);
    });
    return queue;
}


-(BOOL)isDataBaseUpdating
{
    if (!isExhibitorInfoUpdating&&!isCountryUpdating&&!isCategoryUpdating) //没有数据在更新
    {
        return NO;
    }
    else
    {
        return YES;
    }
}

-(NSString*)realmDB
{
    BOOL success;
    //获取本地数据库路径
    NSFileManager* fileManager=[NSFileManager defaultManager];
    NSError* error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [paths objectAtIndex:0];
    NSString *database_path = [documents stringByAppendingPathComponent:@"LocalExhibitorData.realm"];
    //查看该路径下的文件是否存在
    success = [fileManager fileExistsAtPath:database_path];
    if(!success)  //文件不存在
    {
        NSString* defaultDBPath = [[NSBundle mainBundle] pathForResource:@"LocalExhibitorData" ofType:@"realm"];
        
        if(defaultDBPath!=nil) //将本地库写入指定目录中
        {
            success = [fileManager copyItemAtPath:defaultDBPath
                                           toPath:database_path
                                            error:&error];
        }
        if(!success)
        {
            NSLog(@"打开备选数据库失败:%@",error);
        }
    }
    return database_path;
}

-(void)initData
{
    isCountryUpdating = YES;
    isCategoryUpdating = YES;
    isExhibitorInfoUpdating = YES;
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    //更新展商信息
    NSInteger exhibitorInfoV = [user integerForKey:exhibitorInfo];
    if (exhibitorInfoV==0) //本地版本号初始化
    {
        exhibitorInfoV = 0;
        [user setInteger:exhibitorInfoV forKey:exhibitorInfo];
        [user synchronize];
    }
    
    [DKHTTPRequest sendDataWithShortUrl:@"index_version"
                                  Param:[XXTool formatStringWithLanguage:@""]
                             ImageArray:nil
                                TimeOut:10
                             Completion:^BOOL(NSMutableDictionary *serverDic, DKHTTPResponseType bufferType) {
                                 if([[serverDic objectForKey:@"code"] intValue]==200)
                                 {
                                     int serverCategory = [[serverDic objectForKey:@"exhibitor_version"]intValue];
                                     if (exhibitorInfoV<serverCategory)
                                     {
                                         dispatch_async([DBProject realmQueue], ^{
                                             RLMResults *deleteData = [RXMLExhibitorInformationModel allObjectsInRealm:[RLMRealm realmWithPath:_dataName]];
                                             [[RLMRealm realmWithPath:_dataName] beginWriteTransaction];
                                             [[RLMRealm realmWithPath:_dataName] deleteObjects:deleteData];
                                             [[RLMRealm realmWithPath:_dataName] commitWriteTransaction];
                                         });
                                         [self updateExhibitorInfoWithCompletion:^{
                                             //更新类别完成后改变本地版本号和正在更新标识职位no
                                             isExhibitorInfoUpdating = NO;
                                             [user setInteger:serverCategory
                                                       forKey:exhibitorInfo];
                                             [user synchronize];
                                         }];
                                     }
                                     else
                                     {
                                         isExhibitorInfoUpdating = NO;
                                     }
                                 }
                                 else
                                 {
                                     isExhibitorInfoUpdating = NO;
                                 }
                                 return YES;
                             } IsBuffering:NO
                      IsNeedReplaceWrap:NO
                        IsUseUpLoadHead:NO];
    
    
    //更新分类
    NSInteger indexV = [user integerForKey:indexVision];
    if (indexV==0)
    {
        indexV = 0;
        [user setInteger:indexV forKey:indexVision];
        [user synchronize];
    }
    
    [DKHTTPRequest sendDataWithShortUrl:@"index_version"
                                  Param:[XXTool formatStringWithLanguage:@""]
                             ImageArray:nil
                                TimeOut:10
                             Completion:^BOOL(NSMutableDictionary *serverDic, DKHTTPResponseType bufferType) {
                                 if([[serverDic objectForKey:@"code"] intValue]==200)
                                 {
                                     int serverCategory = [[serverDic objectForKey:@"index_version"]intValue];
                                     if (indexV<serverCategory)
                                     {
                                         dispatch_async([DBProject realmQueue], ^{
                                             RLMResults *deleteData = [RXMLExhibitorIndexModel allObjectsInRealm:[RLMRealm realmWithPath:_dataName]];
                                             [[RLMRealm realmWithPath:_dataName] beginWriteTransaction];
                                             [[RLMRealm realmWithPath:_dataName] deleteObjects:deleteData];
                                             [[RLMRealm realmWithPath:_dataName] commitWriteTransaction];
                                         });
                                         [self updateIndexWithCompletion:^{
                                             //更新类别完成后改变本地版本号和正在更新标识职位no
                                             isCategoryUpdating = NO;
                                             [user setInteger:serverCategory
                                                       forKey:indexVision];
                                             [user synchronize];
                                         }];
                                     }
                                     else
                                     {
                                         isCategoryUpdating = NO;
                                     }
                                 }
                                 else
                                 {
                                     isCategoryUpdating = NO;
                                 }
                                 return YES;
                             } IsBuffering:NO
                      IsNeedReplaceWrap:NO
                        IsUseUpLoadHead:NO];
    
    //更新国家
    NSInteger countryV = [user integerForKey:countryIndexVision];
    if (countryV==0)
    {
        countryV = 0;
        [user setInteger:countryV forKey:countryIndexVision];
        [user synchronize];
    }
   
    [DKHTTPRequest sendDataWithShortUrl:@"index_version"
                                  Param:[XXTool formatStringWithLanguage:@""]
                             ImageArray:nil
                                TimeOut:10
                             Completion:^BOOL(NSMutableDictionary *serverDic, DKHTTPResponseType bufferType) {
                                 if([[serverDic objectForKey:@"code"] intValue]==200)
                                 {
                                     int serverCountry = [[serverDic objectForKey:@"country_version"]intValue];
                                     if (countryV<serverCountry)
                                     {
                                         dispatch_async([DBProject realmQueue], ^{
                                             RLMResults *deleteData = [RXMLCountryIndex allObjectsInRealm:[RLMRealm realmWithPath:_dataName]];
                                             [[RLMRealm realmWithPath:_dataName] beginWriteTransaction];
                                             [[RLMRealm realmWithPath:_dataName] deleteObjects:deleteData];
                                             [[RLMRealm realmWithPath:_dataName] commitWriteTransaction];
                                         });
                                         
                                         [self updateCountryWithCompletion:^{
                                             //更新类别完成后改变本地版本号和正在更新标识职位no
                                             isCountryUpdating = NO;
                                             [user setInteger:serverCountry
                                                       forKey:countryIndexVision];
                                             [user synchronize];
                                         }];
                                        
                                     }
                                     else
                                     {
                                         isCountryUpdating = NO;
                                     }
                                 }
                                 else
                                 {
                                     isCountryUpdating = NO;
                                 }
                                 return YES;
                             } IsBuffering:NO
                      IsNeedReplaceWrap:NO
                        IsUseUpLoadHead:NO];
}

/**
 *  类别索引更新
 */
-(void)updateIndexWithCompletion:(void(^)())block
{
    [DKHTTPRequest sendDataWithShortUrl:@"goods_index_list"
                                  Param:[XXTool formatStringWithLanguage:@""]
                             ImageArray:nil
                                TimeOut:10
                             Completion:^BOOL(NSMutableDictionary *serverDic, DKHTTPResponseType bufferType) {
                                 if ([[serverDic objectForKey:@"code"] intValue]==200)
                                 {
                                    
                                     NSArray *tempArray = [serverDic objectForKey:@"exlist"];
                                     
                                     dispatch_async([DBProject realmQueue], ^{
                                         for (int i=0; i<tempArray.count; i++)
                                         {
                                             RXMLExhibitorIndexModel*temp = [RXMLExhibitorIndexModel mj_objectWithKeyValues:tempArray[i]];
                                             temp.index_name_cn = [temp.index_name_cn stringByReplacingOccurrencesOfString:@"\n" withString:@"\r"];
                                             temp.index_name_en = [temp.index_name_en stringByReplacingOccurrencesOfString:@"\n" withString:@"\r"];
                                             [[RLMRealm realmWithPath:_dataName] beginWriteTransaction];
                                             [[RLMRealm realmWithPath:_dataName] addObject:temp];
                                             [[RLMRealm realmWithPath:_dataName] commitWriteTransaction];
                                         }
                                         if (block)
                                         {
                                             block();
                                         }
                                     });        
                                 }
                                 return YES;
                             } IsBuffering:NO
                      IsNeedReplaceWrap:NO
                        IsUseUpLoadHead:NO];
}

/**
 *  国家索引更新
 */
-(void)updateCountryWithCompletion:(void(^)())block
{
    [DKHTTPRequest sendDataWithShortUrl:@"ElcatalogueExhibitorCountryIndex"
                                  Param:[XXTool formatStringWithLanguage:@""]
                             ImageArray:nil
                                TimeOut:10
                             Completion:^BOOL(NSMutableDictionary *serverDic, DKHTTPResponseType bufferType) {
                                 if ([[serverDic objectForKey:@"code"] intValue]==200)
                                 {
                                     
                                     NSArray *tempArray = [serverDic objectForKey:@"list"];
                                     
                                     dispatch_async([DBProject realmQueue], ^{
                                         for (int i=0; i<tempArray.count; i++)
                                         {
                                             RXMLCountryIndex *temp = [RXMLCountryIndex mj_objectWithKeyValues:tempArray[i]];
                                             [[RLMRealm realmWithPath:_dataName] beginWriteTransaction];
                                             [[RLMRealm realmWithPath:_dataName] addObject:temp];
                                             [[RLMRealm realmWithPath:_dataName] commitWriteTransaction];
                                         }
                                         if (block)
                                         {
                                             block();
                                         }
                                     });
                                 }
                                 return YES;
                             } IsBuffering:NO
                      IsNeedReplaceWrap:NO
                        IsUseUpLoadHead:NO];
}

/**
 *  展商信息更新
 *
 *  @param block block
 */
-(void)updateExhibitorInfoWithCompletion:(void(^)())block
{
    [DKHTTPRequest sendDataWithShortUrl:@"ElcatalogueExhibitorDList"
                                  Param:[XXTool formatStringWithLanguage:@""]
                             ImageArray:nil
                                TimeOut:10
                             Completion:^BOOL(NSMutableDictionary *serverDic, DKHTTPResponseType bufferType) {
                                 if ([[serverDic objectForKey:@"code"] intValue]==200)
                                 {
                                     
                                     NSArray *tempArray = [serverDic objectForKey:@"list"];
                                     
                                     dispatch_async([DBProject realmQueue], ^{
                                         for (int i=0; i<tempArray.count; i++)
                                         {
                                             RXMLExhibitorInformationModel *temp = [RXMLExhibitorInformationModel mj_objectWithKeyValues:tempArray[i]];
                                             [[RLMRealm realmWithPath:_dataName] beginWriteTransaction];
                                             [[RLMRealm realmWithPath:_dataName] addObject:temp];
                                             [[RLMRealm realmWithPath:_dataName] commitWriteTransaction];
                                         }
                                         if (block)
                                         {
                                             block();
                                         }
                                     });
                                 }
                                 return YES;
                             } IsBuffering:NO
                      IsNeedReplaceWrap:NO
                        IsUseUpLoadHead:NO];
}

@end
